﻿#include "tcpserver.h"
#include <stdio.h>
#include <string.h>
#include <thread>
#include <mutex>

#ifdef _WIN32
#  include <winsock2.h>      // 所有 socket 函数
#  include <ws2tcpip.h>      // 扩展：sockaddr_in6, inet_pton, inet_ntop...
#  pragma comment(lib, "ws2_32.lib")
using ssizet = int;       // Windows 没有 ssize_t
#else
#  include <sys/socket.h>
#  include <netinet/in.h>
#  include <arpa/inet.h>
#  include <unistd.h>
#  include <sys/types.h>
using ssizet = ssize_t;
#endif

using namespace std;

TcpServer::TcpServer()
{
}

bool TcpServer::start(int port)
{
    if (mStarted)
        return true;

    mSocket = socket(AF_INET, SOCK_STREAM, 0);
    if (mSocket == -1)
    {
        perror("create tcp socket failed: %s");
        return false;
    }

#ifdef _WIN32
    int val = 1;
    auto* p_val = (const char*)&val;
	setsockopt(mSocket, SOL_SOCKET, SO_REUSEADDR, p_val, sizeof(val));
#else
	int val = 1;
	setsockopt(mSocket, SOL_SOCKET, SO_REUSEADDR, &val, sizeof(val));
#endif
   

    sockaddr_in addr;
    addr.sin_family = AF_INET;
    addr.sin_addr.s_addr = htonl(INADDR_ANY);
    addr.sin_port = htons(port);
    int ret = ::bind(mSocket, (sockaddr *)&addr, sizeof(addr));
    if (ret == -1)
    {
        perror("bind failed");
        return false;
    }

    ret = listen(mSocket, 5);
    if (ret == -1)
    {
        perror("listen failed");
        return false;
    }

    mStarted = true;
    thread thd(&TcpServer::keepAccept, this);
    thd.detach();

    return true;
}

void TcpServer::whenNewClient(TcpServer::ClientHandler onClientConnected)
{
    mClientHandler = onClientConnected;
}

void TcpServer::stop()
{
    mStarted = false;

#ifdef _WIN32
    closesocket(mSocket);
#else
    close(mSocket);
#endif
   
}

void TcpServer::keepAccept()
{
    while (mStarted)
    {
        sockaddr_in addr;
        socklen_t len = sizeof(addr);
        int ret = ::accept(mSocket, (sockaddr *)&addr, &len);
        if (ret < 0)
        {
            perror("failed to accept");
            break;
        }

        if (mClientHandler)
        {
            mClientHandler(ret);
        }
    }
}
